package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.ApiTypeEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.enums.RupeeTigerCollectionTagEnum;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.*;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/10
 * Time: 8:49 下午
 */
@Service
public class RupeeTigerService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RupeeTigerService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("creditmuga", this);
        BaseJobHandler.merchantAndServiceMap.put("sareecash", this);
        BaseJobHandler.merchantAndServiceMap.put("rupeebag", this);
        BaseJobHandler.merchantAndServiceMap.put("idliloanin", this);
        BaseJobHandler.merchantAndServiceMap.put("puttu", this);
        BaseJobHandler.merchantAndServiceMap.put("relax", this);
        BaseJobHandler.merchantAndServiceMap.put("rupeeyaaron", this);
        BaseJobHandler.merchantAndServiceMap.put("idli", this);
        BaseJobHandler.merchantAndServiceMap.put("walnutsloan", this);
        BaseJobHandler.merchantAndServiceMap.put("naanloan", this);
        BaseJobHandler.merchantAndServiceMap.put("poppins", this);
        BaseJobHandler.merchantAndServiceMap.put("korma", this);
        BaseJobHandler.merchantAndServiceMap.put("asher", this);
        BaseJobHandler.merchantAndServiceMap.put("pagli", this);
        BaseJobHandler.merchantAndServiceMap.put("selina", this);
        BaseJobHandler.merchantAndServiceMap.put("tenzin", this);
        BaseJobHandler.merchantAndServiceMap.put("drisana", this);
        BaseJobHandler.merchantAndServiceMap.put("rupeedidi", this);
        BaseJobHandler.merchantAndServiceMap.put("pravin", this);
    }

    public String login(String agentCode,String cookie) {
        if (StringUtils.isEmpty(cookie)){
            return "登录失败";
        }
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(agentCode);
        List<CeAgentAccountEntity> accountsMerchantCode = agentAccountDao.getAccountsMerchantCode(agentAccount.getMerchantCode());
        boolean isExist= false;
        CeAgentAccountEntity existAgentAccount=null;
        for (int i = 0; i < accountsMerchantCode.size(); i++) {
            boolean contains = accountsMerchantCode.get(i).getRequestHeader().contains(cookie);
            if (contains){
                isExist=true;
                existAgentAccount= accountsMerchantCode.get(i);
                break;
            }
        }
        if (isExist){
            return "Cookie与 "+existAgentAccount.getAccount()+" 重复";
        }
        LOGGER.info("== tiger 登录接口 ==,cookie:{}", cookie);
        if (StringUtils.isNotEmpty(cookie)) {
            JSONObject requestHeader = new JSONObject();
            requestHeader.put("Cookie","gn_="+ cookie);
            requestHeader.put("Content-Type", "application/json");
            agentAccount.setRequestHeader(requestHeader.toString());
            agentAccount.setLoginDt(new Date());
            agentAccount.setLoginStatus(1);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登录成功";
        } else {
            LOGGER.info("== 请求登录接口 失败 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登录失败";
        }
    }


//    public boolean login(CeAgentAccountEntity agentAccount, String code,String googlecode) {
//        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
//        String url = merchant.getApiDomain() + "/member/index/login";
//        LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
//        Map<String, String> headers = new HashMap<>();
//        headers.put("Content-Type", "application/x-www-form-urlencoded");
//        headers.put("X-Requested-With", "XMLHttpRequest");
//        String SessionId="";
//        String Token="";
//        String Sig="";
//        if (agentAccount.getMerchantCode().equals("holiloanin")){
//            SessionId="010B3TrWzwsdkM2Lqh18cIU-6K9HxVgrWWJbub4rcqyn8Xx3V_xrEI23ZJ54GzxVlXUJ64RvP97tYtwjQoXiP_QNILksAsi_jOiYiArUQCcwdB868MvOl8tcUwL1pP4CneX9gEEXy51a8ASay8dpaIwaHVcVwpGAbk-y5IjlmyqJi6UoHbY4RqyEHBYghRItwlnALcbseNIzyI6tVyQ-jUIA";
//            Token="FFFF0N0000000000AF0E:1662775177341:0.7518344923679614";
//            Sig="05XqrtZ0EaFgmmqIQes-s-CDKLKjRHEghL5py5_qB_vPvDA5lM4EFeJFYUIcKn0ncx3e1_oG92h7nqZXUTvG2hTnV4f6x_A8V5dxHcNUtJ1r9c61lO4c5xF4cmdomh5dU6OWgWEJCl5QPP0t9iS7Bx-KRZA8UHYHJzoypfPa5WLApqWH1o4vGpnnVF3zNa9ZXllb7fmVyo0yMgrhfi1qoOzoishx19QswKWOplgzN6DvCJ5qhY_MrcYaNOV0HVaB0v01Ar3YahFiLVfGqfBS59zrWzS6a09Liwp_8GxdDN7tyReojM1oEHb6vBgruCBBeCy0XwqLPmN-kkkqNmn9CcODAhHoW9vt3dPjGwNvsdFzuDZ__5ddyoLqvoHype1i1RQA8sozL9Dmcdd9FOzudcKD0ZFS1mz4z4HP5D9PkHdQSuUNRlnjFGwRorut-r58rSajM9vxCC-go21ql2uu8BJ73vCQDPkUC-BQvcnJT13SI";
//        }else if (agentAccount.getMerchantCode().equals("samosa")){
//            SessionId="010B3TrWzwsdkM2Lqh18cIUzjDfuk1_d72hEss0EL82xr1agSxaI-gaDaU_PyFPs-iL9dZHpb4OD8HE5z0ETHXytILksAsi_jOiYiArUQCcwdB868MvOl8tcUwL1pP4Cneb2u_z6HnjSauRZ9q6drj5IY_ojT9kcXynoY-yJvVmhK6UoHbY4RqyEHBYghRItwlnALcbseNIzyI6tVyQ-jUIA";
//            Token="FFFF0N0000000000AF0E:1662775487029:0.5071369774618931";
//            Sig="05XqrtZ0EaFgmmqIQes-s-CDKLKjRHEghL5py5_qB_vPvDA5lM4EFeJFYUIcKn0ncxKdtm6jEpiHcpTJLWFvpN_ZBUwB9lguAT4EDkMZtaMNtc61lO4c5xF4cmdomh5dU6P_70SpzmIurafGKiVCqwiIQSqPfN-KiWClYnyAV36niEPxsb92uz-cJZeS2NWJhm2EjxIqls4lFTz74yo19TcSc4fUdE0q9C9c43HagWIu-J5qhY_MrcYaNOV0HVaB0v01Ar3YahFiLVfGqfBS59zgekEUDb4RKnIh9vO1dqdz91tfw0L6_bgKE_Qk_85q3Wg7yuk3OGBFrJ67rvDmVfwjAhHoW9vt3dPjGwNvsdFzuDZ__5ddyoLqvoHype1i1RGan_qH8urtijxkNRPyqHuz0ZFS1mz4z4HP5D9PkHdQSppyZDng6uL-iP-zEB7hDiQPovs_Gh9o_gsiVWTSdozZP89vZT4h6XayN7o3sz1Q8";
//        }else if (agentAccount.getMerchantCode().equals("amlacredit")){
//            SessionId="01meJRDQhjKvuhvkU5cu47-Ik8mj_oQjrWFoBuAaa6gL-GE43GwBkqzmCCklGZBPmTXh5-lYrYekq-rNnmIocqL_0gAr0O8tIId3dMSMVprRhgj08S1T5hVVoDayX289iJTH1aD2rAAzqsoJqAkX3H9GeRqvatJ22FqzmLI4T3rSgxssffgdmnjxqRIoqkWjEvVCcgR9rW9P1ZVJqv_U-Gzw";
//            Token="FFFF0N0000000000AF0E:1662775049375:0.33754675938755774";
//            Sig="05XqrtZ0EaFgmmqIQes-s-CPuO7eUf-4skZh5VvezA9HnDA5lM4EFeJFYUIcKn0ncxBe_mg_oY3i19zSaJNZKNFnfrVDP0yvtVA_ZScFiS9Ixg7wEoevct_fcCivXMzeYLv-_8u-i0ZFWVuKt7eXuBq53mL6ghOLvubn2-MIAcCxzAgLBAGqnv8UaIXbEq6ED65Yv9pRnehR84a3zjieat-sKfEqMP0tNoSnUrhhPLE6-PuqhHIKg-Xq1epdkhFh7mExhygtd82qIZTMnCDt79ITkWhkmBMyBwXHybvB7Kjw0l4pEsWLhJrcOnAI5KYQ0H7ZmI5oNnKth-zmJMl7RFzVfVe-zP5H3J8pcd0vUVhS2L3b0iJ37RAAXm0vm_I7UIo68VwvfDqw0Y_liINxVtyB7lj5PMEC7aMIdwlPReGalW-qGgoxQgRniyz2xMuKMlIwWufEoNoeiB2kvLcacG9iUkccj3ZSvF2o6szMJNZZk";
//        }else if (agentAccount.getMerchantCode().equals("honeyloanin")){
//            SessionId="01meJRDQhjKvuhvkU5cu47-LWGFHb3vkr9KcoHNCHlBRoZzt4HtRiWCpnaFb71Xa89iZ_uJrOh4wrzjvDVCnK0T_0gAr0O8tIId3dMSMVprRhgj08S1T5hVVoDayX289iJYcbpnEupgCqO9vFEIRwhKK9AMFRY8QpZInzISFvl_14xssffgdmnjxqRIoqkWjEvVCcgR9rW9P1ZVJqv_U-Gzw";
//            Token="FFFF0N0000000000AF0E:1662775455203:0.14439814672599116";
//            Sig="05XqrtZ0EaFgmmqIQes-s-CPuO7eUf-4skZh5VvezA9HnDA5lM4EFeJFYUIcKn0ncxqkfLOuZdsaqQngsKtagWf9UJ6FPSHgx46sy9iYjob91g7wEoevct_fcCivXMzeYL8yjXpCBm4B3o15gWc7oqu1kZCeQgdt0a-jWVf91JLs1gIoBl-9RTec8_P6B_lDZDLn9yIrmbPkDfXkdpOttCU82E9TIs7uXOIeLfMBoqCGiPuqhHIKg-Xq1epdkhFh7mExhygtd82qIZTMnCDt79IfZ1NE67LCXvp47VbgYwu8gaSzhqP-bCkKqKfHXo7-iPArLAqbZBkK5v8ISTNGl4NVfVe-zP5H3J8pcd0vUVhS2L3b0iJ37RAAXm0vm_I7UI0HGAK5o1MVDvOWtdcjh4UB7lj5PMEC7aMIdwlPReGaly82LDMr5rE3iMGmEWoAAf_yi8L5xxzWdcjg9jllu3dNaT8J6Ka9QxVWlVshUvptw";
//        }
//        String params = "username=" + agentAccount.getAccount() + "&password=" + agentAccount.getPassword() + "&googlecode="+googlecode+"&txcode=success&SessionId="+SessionId+"&Token="+Token+"&Sig="+Sig+"&Scene=nc_login&yzcode=123456";
//
//
//        String cookie = HttpUtil.postPageSuccessCookie(url, headers, params);
//        LOGGER.info("== RupeeTiger 登录成功  ==,cookie:{}", cookie);
//        if (StringUtils.isNotEmpty(cookie)) {
//            JSONObject requestHeader = new JSONObject();
//            String cookies = cookie.substring(0, cookie.indexOf(";"));
//            requestHeader.put("cookie", cookies);
//            requestHeader.put("Content-Type", "application/json");
//            agentAccount.setRequestHeader(requestHeader.toString());
//            agentAccount.setLoginDt(new Date());
//            agentAccount.setLoginStatus(1);
//            agentAccountDao.updateByPrimaryKey(agentAccount);
//            return true;
//        } else {
//            LOGGER.info("== 自动登录失败 ==");
//            agentAccount.setLoginStatus(2);
//            agentAccountDao.updateByPrimaryKey(agentAccount);
//            return false;
//        }
//
//
//    }


    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            return false;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/member";
        LOGGER.info("== 检测登陆 开始请求订单列表 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(url, params, headers);
        if (result.contains("Log in")) {
            LOGGER.error("== 请求接口成功 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
        }
        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {

        updateOrderList(agentAccount);
        updateOrderDetailInfo(agentAccount);
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        if (agentAccount.getStage().contains("admin")) {
            return;
        }
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        int perPage = 15;
        List<RupeeTigerTableElement> resultsList = new ArrayList<>();
        Elements trs;
        for (int m = 1; m <= 10; m++) {
            String url = merchant.getApiDomain() + "/member/bebt/rapid_borrow/" + m;
            LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
            Map<String, String> headers = getHeaders(agentAccount);
            Map<String, String> params = Maps.newHashMap();
            String result = HttpUtil.getPage(url, params, headers);

            Document document = Jsoup.parse(result);
            trs = document.select("table").select("tr");

            for (int i = 1; i < trs.size(); i++) {
                RupeeTigerTableElement element = new RupeeTigerTableElement();
                Elements tds = trs.get(i).select("td");
                LOGGER.info("== 开始请求订单列表 ==,tds:{},agentCode:{}", tds,agentAccount.getAgentCode());

                for (int j = 0; j < tds.size(); j++) {
                    if (tds.get(j).childNodes().size() <= 0) {
                        continue;
                    }
                    String value = tds.get(j).childNodes().get(0).toString();

                    if (value.contains(" ")) {
                        value = value.replaceAll(" ", "").trim();
                    }
                    if (j == 1) {
                        element.setId(value);
                    } else if (j == 2) {
                        element.setReloan(Integer.parseInt(value) > 1);
                    } else if (j == 4) {
                        List<Node> nodes = tds.get(j).childNodes();
                        for (int k = 0; k < nodes.size(); k++) {
                            if (k == 0) {
                                element.setName(nodes.get(k).toString());
                            } else if (k == 3) {
                                element.setPhone(nodes.get(k).childNodes().get(0).toString());
                            }
                        }
                    } else if (j == 5) {
                        List<Node> nodes = tds.get(j).childNodes();
                        for (int k = 0; k < nodes.size(); k++) {
                            if (k == 0) {
                                String val = nodes.get(k).toString();
                                element.setLoanTime(val.substring(0, val.indexOf("(Due time")).replaceAll(" ", ""));
                                element.setDueDate(val.substring(val.indexOf("Due time") + 9, val.length() - 1));
                            } else if (k == 2) {
                                element.setOrderNo(nodes.get(k).toString().replaceAll(" ", ""));
                            }
                        }
                    } else if (j == 6) {
                        List<Node> nodes = tds.get(j).childNodes();
                        String loanAmount = nodes.get(3).childNodes().get(0).toString();
                        loanAmount = loanAmount.substring(0, loanAmount.indexOf("【"));
                        element.setLoanAmount(loanAmount);
                    } else if (j == 8) {
                        element.setRepaymentStatus(value);
                    } else if (j == 9) {
                        List<Node> nodes = tds.get(j).childNodes();
                        for (int k = 0; k < nodes.size(); k++) {
                            if (k == 1) {
                                String val = nodes.get(k).childNodes().get(0).toString();
                                element.setOverdueDays(val);
                            } else if (k == 4) {
                                List<Node> childNodes = nodes.get(k).childNodes();
                                if (childNodes.size() > 0) {
                                    for (int z = 0; z < childNodes.size(); z++) {
                                        if (z == 1) {
                                            element.setLateFee(childNodes.get(z).childNodes().get(0).toString());
                                        } else if (z == 5) {
                                            element.setRepaymentAmount(childNodes.get(z).childNodes().get(0).toString());
                                        }
                                    }
                                }
                            }

                        }

                    } else if (j == 10) {
                        String paymentLink = tds.get(j).childNodes().get(0).childNodes().get(0).toString();
                        if (paymentLink.contains("amp;")) {
                            paymentLink = paymentLink.replace("amp;", "");
                        }
                        element.setPaymentLink(paymentLink);
                    } else if (j == 14) {
                        List<Node> nodes = tds.get(j).childNodes();
                        for (int k = 0; k < nodes.size(); k++) {
                            if (nodes.get(k).childNodes().size() <= 0) {
                                continue;
                            }
                            String href = nodes.get(k).attributes().get("href");
                            String customId = href.substring(href.lastIndexOf("/") + 1);
                            element.setCustomId(customId);
                        }
                    }

                }
                if (StringUtils.isNotEmpty(element.getOrderNo()) && !element.getLoanAmount().equals("0")) {
                    resultsList.add(element);
                }
            }
            if (trs.size() < perPage) {
                break;
            }
        }
        if (resultsList.size() == 0) {
            LOGGER.error("== 请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }
        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());


        //对比订单数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            LOGGER.info("== 存在未拉取订单 ==，agentCode:{},size:{}", agentAccount.getAgentCode(), resultsList.size());
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.getOrderNo();
                    CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (todayOneByOrderNo == null) {
                        LOGGER.info("==更新的时候发现有新的订单==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(JsonStream.serialize(item))
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), item.getOrderNo(), e);
                }
            });
        } else {
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.getOrderNo();
                    CeOrdersEntity OneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (OneByOrderNo == null) {
                        LOGGER.info("== 列表为空,插入订单 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(JsonStream.serialize(item))
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), item.getOrderNo(), e);
                }
            });
            LOGGER.info("== 订单减少 ==,agentCode:{}，size:{}", agentAccount.getAgentCode(), resultsList.size());
            activeOrders.forEach(item -> {
                try {
                    String id = item.getOrderNo();
                    boolean hasOrder = false;
                    for (int i = 0; i < resultsList.size(); i++) {
                        RupeeTigerTableElement rupeeTigerTableElement = resultsList.get(i);
                        String orderNo = rupeeTigerTableElement.getOrderNo();
                        if (id.equals(orderNo)) {
                            LOGGER.info("== 当前订单存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                            hasOrder = true;
                            break;
                        }

                    }
                    if (!hasOrder) {
                        LOGGER.info("== 当前订单不存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), id);
                        if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            item.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 更新订单发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
                }
            });

        }

        LOGGER.info("== 订单刷新处理完成 ==");

    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> dialHeaders = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
                String orderId = orderInfo.get("customId").toString();
                Map<String, String> infoMap = new HashMap<>();
                String baseInfoUrl = merchant.getApiDomain() + "/member/bebt/customer_view/" + orderId;
                String baseInfo = HttpUtil.getPage(baseInfoUrl, params, headers);
                LOGGER.info("== 获取成功 repaymentInfo==");

                Document document = Jsoup.parse(baseInfo);
                Elements tables = document.select("tbody");
                if (tables.size() == 0) {
                    return;
                }

                RupeeTigerRepaymentInfoVo repaymentInfoVo = new RupeeTigerRepaymentInfoVo();
                int repayPosition = 0;
                for (int i = 0; i < tables.size(); i++) {
                    if (tables.get(i).toString().contains("Expire date")) {
                        repayPosition=i;
                    }
                }
//                if (tables.size() > 8) {
//                    repayPosition = 5;
//                } else if (tables.size() < 8 && tables.size() > 5) {
//                    repayPosition = 3;
//                } else {
//                    repayPosition = 2;
//                }
//                Elements repaymentTrs = tables.get(repayPosition).select("tr");
//                if (repaymentTrs.toString().contains("自动调额")) {
//                    repayPosition = 5;
//                }
                Elements repaymentTrs = tables.get(repayPosition).select("tr");
                for (int i = 0; i < repaymentTrs.size(); i++) {
                    Elements tds = repaymentTrs.get(i).select("td");
                    for (int j = 0; j < tds.size(); j++) {
                        if (tds.get(j).childNodes().size() <= 0) {
                            continue;
                        }
                        String value = tds.get(j).childNodes().get(0).toString();
                        if (value.contains(" ")) {
                            value = value.replaceAll(" ", "").trim();
                        }
                        if (i == 1 && j == 0) {
                            repaymentInfoVo.setOrderNo(value);
                        } else if (i == 1 && j == 1) {
                            repaymentInfoVo.setAmount(value);
                        } else if (i == 1 && j == 2) {
                            repaymentInfoVo.setExpireDate(value);
                        } else if (i == 1 && j == 4) {
                            repaymentInfoVo.setStatus(tds.get(j).childNodes().get(0).childNodes().get(0).toString());
                        }
                    }
                }
                infoMap.put("repaymentInfo", JsonStream.serialize(repaymentInfoVo));
                String remainMoney = repaymentInfoVo.getAmount();
                updateRemainMoney(order.getCollectionNo(), remainMoney);

                if (!hasDetailData) {

                    Elements baseTrs = tables.get(1).select("tr");
                    RupeeTigerBasicData rupeeTigerBasicData = new RupeeTigerBasicData();
                    for (int i = 0; i < baseTrs.size(); i++) {
                        Elements tds = baseTrs.get(i).select("td");
                        for (int j = 0; j < tds.size(); j++) {
                            if (tds.get(j).childNodes().size() <= 0) {
                                continue;
                            }
                            String value = tds.get(j).childNodes().get(0).toString();
                            if (value.contains(" ")) {
                                value = value.replaceAll(" ", "").trim();
                            }
                            if (i == 1 && j == 0) {
                                rupeeTigerBasicData.setName(tds.get(j).childNodes().get(0).toString());
                            } else if (i == 1 && j == 3) {
                                rupeeTigerBasicData.setAadhaarNo(value);
                            } else if (i == 1 && j == 4) {
                                rupeeTigerBasicData.setPanNo(value);
                            } else if (i == 1 && j == 6) {
                                rupeeTigerBasicData.setPhone(value);
                            }
                        }
                    }

                    infoMap.put("personalInfo", JsonStream.serialize(rupeeTigerBasicData));
                    JSONArray contacts = new JSONArray();
                    int emergencyContactPosition = -1;
                    for (int i = 0; i < tables.size(); i++) {
                        if (tables.get(i).toString().contains("Phone number：")) {
                            emergencyContactPosition=i;
                        }
                    }
                    if (emergencyContactPosition==-1){
                        JSONObject j1 = new JSONObject();
                        j1.put("name", rupeeTigerBasicData.getName());
                        j1.put("phone", rupeeTigerBasicData.getPhone());
                        contacts.add(j1);
                        JSONObject j2 = new JSONObject();
                        j2.put("name", rupeeTigerBasicData.getName());
                        j2.put("phone", rupeeTigerBasicData.getPhone());
                        contacts.add(j2);
                        infoMap.put("emergencyContactInfo", contacts.toString());
                    }else {
                        if (tables.get(3).select("tr").toString().contains("自动调额")) {
                            if (tables.size() != 8) {
                                Elements contactTrs = tables.get(2).select("tr");
                                for (int i = 0; i < contactTrs.size(); i++) {
                                    Elements tds = contactTrs.get(i).select("td");
                                    JSONObject j1 = new JSONObject();
                                    for (int j = 0; j < tds.size(); j++) {
                                        if (tds.get(j).childNodes().size() <= 0) {
                                            continue;
                                        }
                                        String value = tds.get(j).childNodes().get(0).toString();
                                        if (value.contains(" ")) {
                                            value = value.replaceAll(" ", "").trim();
                                        }
                                        if (j == 0) {
                                            j1.put("name", value);
                                        } else if (j == 1) {
                                            String phone = value.substring(value.indexOf("：") + 1);
                                            j1.put("phone", phone);

                                        }
                                    }
                                    contacts.add(j1);
                                }
                                infoMap.put("emergencyContactInfo", contacts.toString());
                            }
                        } else {
                            Elements contactTrs = tables.get(2).select("tr");
                            for (int i = 0; i < contactTrs.size(); i++) {
                                Elements tds = contactTrs.get(i).select("td");
                                JSONObject j1 = new JSONObject();
                                for (int j = 0; j < tds.size(); j++) {
                                    if (tds.get(j).childNodes().size() <= 0) {
                                        continue;
                                    }
                                    String value = tds.get(j).childNodes().get(0).toString();
                                    if (value.contains(" ")) {
                                        value = value.replaceAll(" ", "").trim();
                                    }
                                    if (j == 0) {
                                        j1.put("name", value);
                                    } else if (j == 1) {
                                        String phone = value.substring(value.indexOf("：") + 1);
                                        j1.put("phone", phone);

                                    }
                                }
                                contacts.add(j1);
                            }
                            infoMap.put("emergencyContactInfo", contacts.toString());
                        }
                    }

                    List<String> imgaes = Lists.newArrayList();
                    Elements imgDivs = document.select("img");
                    for (int i = 0; i < imgDivs.size(); i++) {
                        String img = imgDivs.get(i).attributes().get("data-src");
                        if (StringUtils.isNotEmpty(img)) {
                            imgaes.add(img);
                        }
                    }
                    infoMap.put("images", JsonStream.serialize(imgaes));

                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {
                        try {
                            String dialUrl = merchant.getApiDomain() + "/member/shgl/contact/" + orderId;
                            String contactInfo = HttpUtil.getPage(dialUrl, params, dialHeaders);
                            Document contactDocument = Jsoup.parse(contactInfo);
                            JSONArray contactsList = new JSONArray();
                            Elements contactsTables = contactDocument.select("tbody");
                            JSONObject jsonData = new JSONObject();
                            if (contactsTables.size() == 0) {
                                jsonData.put("contacts", contacts);
                                LOGGER.info("== 通讯录为空，上传紧急联系人 ==,order:{}", order.getOrderNo());
                            } else {
                                Elements contactListTrs = contactsTables.get(0).select("tr");
                                int size = Math.min(contactListTrs.size(), 500);
                                for (int i = 1; i < size; i++) {
                                    Elements tds = contactListTrs.get(i).select("td");
                                    JSONObject j1 = new JSONObject();
                                    for (int j = 0; j < tds.size(); j++) {
                                        if (tds.get(j).childNodes().size() <= 0) {
                                            continue;
                                        }
                                        String value = tds.get(j).childNodes().get(0).toString();
                                        if (value.contains(" ")) {
                                            value = value.replaceAll(" ", "").trim();
                                        }
                                        if (j == 0) {
                                            j1.put("name", value);
                                        } else if (j == 1) {
                                            String phone = value.substring(value.indexOf("：") + 1);
                                            j1.put("phone", phone);
                                        }
                                    }
                                    if (j1.size() > 0) {
                                        contactsList.add(j1);
                                    }
                                }
                                jsonData.put("contacts", contactsList);
                                if (contacts.size() == 0) {
                                    for (int i = 1; i < 3; i++) {
                                        Elements tds = contactListTrs.get(i).select("td");
                                        JSONObject j1 = new JSONObject();
                                        for (int j = 0; j < tds.size(); j++) {
                                            if (tds.get(j).childNodes().size() <= 0) {
                                                continue;
                                            }
                                            String value = tds.get(j).childNodes().get(0).toString();
                                            if (value.contains(" ")) {
                                                value = value.replaceAll(" ", "").trim();
                                            }
                                            if (i > 0) {
                                                if (j == 0) {
                                                    j1.put("name", value);
                                                } else if (j == 1) {
                                                    String phone = value.substring(value.indexOf("：") + 1);
                                                    j1.put("phone", phone);

                                                }
                                            }
                                        }
                                        if (j1.size() > 0) {
                                            contacts.add(j1);
                                        }
                                    }
                                    infoMap.put("emergencyContactInfo", contacts.toString());
                                }

                            }

                            String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                            infoMap.put("contactUrl", contactUrl);

                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });

                    order.setSyncStatus(OrderSyncStatusEnum.waiting.getStatus());
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any repaymentInfo = JsonIterator.deserialize(order.getOrderInfo());

                String appName = agentAccount.getAppName();
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");


                String borrowCapital = repaymentInfo.get("loanAmount").toString();
                String actualAmount = repaymentInfo.get("loanAmount").toString();
                String paidAmount = "0";
                String remainMoney = repaymentInfo.get("repaymentAmount").toString();
                String serviceFee = "0";
                String overdueDays = repaymentInfo.get("overdueDays").toString();
                String lateFee = repaymentInfo.get("lateFee").toString();

                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                String overdueRatio = "0";
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }
                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity repaymentInfoTWO = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfoTWOJson = JsonIterator.deserialize(repaymentInfoTWO.getDetailInfo());

                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(repaymentInfo.get("isReloan").toBoolean() ? 2 : 1)
                        .setBorrowCapital(borrowCapital)
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest("0")
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceFee)
                        .setLateServiceFee("0")
                        .setReceivedCapital(actualAmount)
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(repaymentInfo.get("loanTime").toString())
                        .setRepaymentDate(repaymentInfoTWOJson.get("expireDate").toString())
                        .setRemainMoney(remainMoney)
                        .setTotalMoney(remainMoney);

                request.setOrderInfo(orderInputVo);


                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "personalInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());

                String aadhaarNo = personalInfoJson.get("aadhaarNo").toString();
                String pancardNo = personalInfoJson.get("panNo").toString();
                String email = "no";
                String mobile = personalInfoJson.get("phone").toString();
                String name = personalInfoJson.get("name").toString();
                int gender = 0;
                int maritalStatus = 0;
                int education = 0;
                String address = "no";
                String pinCode = "no";
                String state = "no";
                String city = "no";
                String birthDay = DateUtil.getDate("yyyy-MM-dd");


                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "emergencyContactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() >= 2) {
                    parentName = contactInfoJson.get(0).get("name").toString();
                    parentPhone = contactInfoJson.get(0).get("phone").toString();
                    friendName = contactInfoJson.get(1).get("name").toString();
                    friendMobile = contactInfoJson.get(1).get("phone").toString();
                }


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                List<Any> anies = JsonIterator.deserialize(iamges.getDetailInfo()).asList();

                List<String> images = new ArrayList<>();
                anies.forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(address)
                        .setBirthday(birthDay)
                        .setCity(city)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(education)
                        .setKycNo(aadhaarNo)
                        .setMobile(mobile)

                        .setMarriedStatus(maritalStatus)
                        .setMarriedStatus(maritalStatus)
                        .setName(name)
                        .setPinCode(pinCode)
                        .setState(state)

                        .setSex(gender)
                        .setContactUrl(contactUrlEntity.getDetailInfo())
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }


    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        CeAgentAccountEntity admin = null;
        if (agentAccount.getMerchantCode().equals("creditmuga")) {
            admin = agentAccountDao.getByAgentCode("creditmugaadmin");
        } else if (agentAccount.getMerchantCode().equals("sareecash")) {
            admin = agentAccountDao.getByAgentCode("sareecashadmin");
        } else if (agentAccount.getMerchantCode().equals("rupeebag")) {
            admin = agentAccountDao.getByAgentCode("rupeebagadmin");
        } else if (agentAccount.getMerchantCode().equals("idliloanin")) {
            admin = agentAccountDao.getByAgentCode("idliloaninadmin");
        } else if (agentAccount.getMerchantCode().equals("puttu")) {
            admin = agentAccountDao.getByAgentCode("puttuadmin");
        } else if (agentAccount.getMerchantCode().equals("relax")) {
            admin = agentAccountDao.getByAgentCode("relaxadmin");
        } else if (agentAccount.getMerchantCode().equals("rupeeyaaron")) {
            admin = agentAccountDao.getByAgentCode("rupeeyaaronadmin");
        } else if (agentAccount.getMerchantCode().equals("poppins")) {
            admin = agentAccountDao.getByAgentCode("poppinsadmin");
        } else if (agentAccount.getMerchantCode().equals("idli")) {
            admin = agentAccountDao.getByAgentCode("idliadmin");
        } else if (agentAccount.getMerchantCode().equals("walnutsloan")) {
            admin = agentAccountDao.getByAgentCode("walnutsloanadmin");
        }  else if (agentAccount.getMerchantCode().equals("naanloan")) {
            admin = agentAccountDao.getByAgentCode("naanloanadmin");
        } else if (agentAccount.getMerchantCode().equals("korma")) {
            admin = agentAccountDao.getByAgentCode("kormaadmin");
        } else if (agentAccount.getMerchantCode().equals("asher")) {
            admin = agentAccountDao.getByAgentCode("asheradmin");
        } else if (agentAccount.getMerchantCode().equals("pagli")) {
            admin = agentAccountDao.getByAgentCode("pagliadmin");
        } else if (agentAccount.getMerchantCode().equals("selina")) {
            admin = agentAccountDao.getByAgentCode("selinaadmin");
        } else if (agentAccount.getMerchantCode().equals("tenzin")) {
            admin = agentAccountDao.getByAgentCode("tenzinadmin");
        } else if (agentAccount.getMerchantCode().equals("drisana")) {
            admin = agentAccountDao.getByAgentCode("drisanaadmin");
        } else if (agentAccount.getMerchantCode().equals("rupeedidi")) {
            admin = agentAccountDao.getByAgentCode("rupeedidiadmin");
        } else if (agentAccount.getMerchantCode().equals("pravin")) {
            admin = agentAccountDao.getByAgentCode("pravinadmin");
        }
        if (admin == null) {
            LOGGER.info("== 管理员账号未配置 ==,account:{}", agentAccount.getAccount());
            return;
        }
        Map<String, String> headers = getHeaders(admin);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        Map<String, String> params = Maps.newHashMap();
        String url = merchant.getApiDomain() + "/member/statisticsdata/buybackhbyorders?csyname=" + agentAccount.getAccount() + "&btime=" + DateUtil.getDate("yyyy-MM-dd") + "&etime=" + DateUtil.getDate("yyyy-MM-dd");
        LOGGER.info("== 开始请求已还款订单列表 ==,url:{}", url);
        String result = HttpUtil.getPage(url, params, headers);
        LOGGER.info("== RupeeTiger还款详情 ==,result:{}", result);
        Document document = Jsoup.parse(result);
        Elements trs = document.select("table").select("tr");
        if (trs.size() <= 0) {
            LOGGER.info("== 请求已还款订单列表出错 ==,account:{}", agentAccount.getAccount());
            return;
        }
        JSONArray repayList = new JSONArray();

        for (int i = 1; i < trs.size(); i++) {
            Elements tds = trs.get(i).select("td");
            JSONObject detail = new JSONObject();
            for (int j = 0; j < tds.size(); j++) {
                if (tds.get(j).childNodes().size() <= 0) {
                    continue;
                }
                String value = tds.get(j).childNodes().get(0).toString();
                if (j == 0) {
                    detail.put("name", value);
                } else if (j == 1) {
                    detail.put("phone", value);
                } else if (j == 2) {
                    detail.put("amount", value);
                }
            }
            repayList.add(detail);
        }

        String extUrl = merchant.getApiDomain() + "/member/statisticsdata/buybackhbyorders1?csyname=" + agentAccount.getAccount() + "&btime=" + DateUtil.getDate("yyyy-MM-dd") + "&etime=" + DateUtil.getDate("yyyy-MM-dd");
        LOGGER.info("== 开始请求展期订单列表 ==,url:{}", extUrl);
        String extResult = HttpUtil.getPage(extUrl, params, headers);
        LOGGER.info("== RupeeTiger还款详情 ==,result:{}", extResult);
        Document extDocument = Jsoup.parse(extResult);
        Elements extTtrs = extDocument.select("table").select("tr");
        if (extTtrs.size() <= 0) {
            LOGGER.info("== 请求已还款订单列表出错 ==,account:{}", agentAccount.getAccount());
            return;
        }
        for (int i = 1; i < extTtrs.size(); i++) {
            Elements tds = extTtrs.get(i).select("td");
            JSONObject detail = new JSONObject();
            for (int j = 0; j < tds.size(); j++) {
                if (tds.get(j).childNodes().size() <= 0) {
                    continue;
                }
                String value = tds.get(j).childNodes().get(0).toString();
                if (j == 0) {
                    detail.put("name", value);
                } else if (j == 1) {
                    detail.put("phone", value);
                } else if (j == 2) {
                    detail.put("amount", value);
                }
            }
            repayList.add(detail);
        }

        LOGGER.info("====", repayList.toString());
        waitingPaidCheckOrders.forEach(order -> {
            Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
            String phone = orderDetail.get("phone").toString();
            String name = orderDetail.get("name").toString();
            String repaymentAmount = orderDetail.get("repaymentAmount").toString();
            boolean isRepay = false;
            for (int i = 0; i < repayList.size(); i++) {
                LOGGER.info("==RupeeTiger 还款金额==,name:{},amountL:{},repaymentAmount:{}", name, repayList.getJSONObject(i).getString("amount"), repaymentAmount);
                if (phone.equals(repayList.getJSONObject(i).getString("phone")) && name.contains(repayList.getJSONObject(i).getString("name"))) {
                    isRepay = true;
                    break;
                }
            }
            if (isRepay) {
                LOGGER.info("== 订单已还款 ==,OrderNo:{}", order.getOrderNo());
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                order.setStatus(OrderStatusEnum.paid_update.getStatus());
                ordersDao.updateByPrimaryKey(order);
                return;
            }
            LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
            order.setStatus(OrderStatusEnum.removed.getStatus());
            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
            ordersDao.updateByPrimaryKey(order);
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any deserialize = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
                String paidAmount = deserialize.get("amount").toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });

    }

    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any deserialize = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
//                String paidAmount = deserialize.get("paidAmount").toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });

    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }

    /**
     * @param ceCommentPushLogEntity
     * @return 1 connected   1-7 willingness-to-repay
     * 1-11 willing to repay
     * 1-5 虚假个人信息
     * 2  no-answer
     * 3  empty-number / halt / shutdown
     * 4  reject / hang-up / pull-black
     */
    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        LOGGER.info("== 开始同步催记到甲方 ==");
        RupeeTigerCollectionTagEnum currentTag = RupeeTigerCollectionTagEnum.RNR_V2;

        for (RupeeTigerCollectionTagEnum e : RupeeTigerCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }

        try {
            CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
            CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
            CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceCommentPushLogEntity.getMerchantCode(), "personalInfo", ceCommentPushLogEntity.getOriginNo());

            CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(personalInfo.getOrderNo());
            Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
            String url = ceMerchantEntity.getApiDomain() + "/member/bebt/add_visit/" + orderInfo.get("customId").toString();
            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("info[type]", currentTag.getCpType() + "")
                    .addFormDataPart("info[content]", currentTag.getShortDesc())
                    .addFormDataPart("info[exhibit]", "")
                    .addFormDataPart("dosubmit", "")
                    .build();
            Map<String, String> header = getHeaders(account);
            header.put("X-Requested-With", "XMLHttpRequest");
            String result = HttpUtil.postFormDatas(url, header, body);
            if (result.contains("添加成功！")) {
                LOGGER.info("== RupeeTiger 同步催记到甲方 成功==,res:{}", result);
                return true;
            } else {
                LOGGER.info("== RupeeTiger 同步催记到甲方 异常==,res:{}", result);
            }
        } catch (Exception e) {
            LOGGER.info("== cbcash 开始同步催记到甲方 异常==", e);
            return false;
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());

        String link = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo()).get("paymentLink").toString();

        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());

        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        String renewLink = "";
        return renewLink;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String
            remark, String amount) {
        return "";
    }

    public static String getLastDayDate(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(DateUtil.getDate(date, "yyyy-MM-dd"));
        c.add(Calendar.DATE, -1);
        Date start = c.getTime();
        return format.format(start);
    }

    @Override
    public String queryPaymentOrderResult(String orderNo, String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {

        return "";
    }

    public static void main(String[] args) {
        String extResult = "<!DOCTYPE html>\n" +
                "<html lang=\"zh-CN\">\n" +
                "<head>\n" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">\n" +
                "<meta name=\"robots\" content=\"noindex,nofollow\" />\n" +
                "<title>Rupee Tiger</title>\n" +
                "<link href=\"http://b.rupeetigerloan.com:8080/statics/css/bootstrap.min.css\" rel=\"stylesheet\">\n" +
                "<link type=\"text/css\" href=\"http://b.rupeetigerloan.com:8080/statics/css/font-awesome.min.css\" rel=\"stylesheet\" />\n" +
                "<link type=\"text/css\" href=\"http://b.rupeetigerloan.com:8080/statics/css/jquery.dataTables.min.css\" rel=\"stylesheet\" />\n" +
                "<link rel=\"stylesheet\" href=\"http://b.rupeetigerloan.com:8080/statics/css/ui-dialog.css\">\n" +
                "<!--[if IE 7]>\n" +
                "<link rel=\"stylesheet\" href=\"http://b.rupeetigerloan.com:8080/statics/css/font-awesome-ie7.min.css\">\n" +
                "<![endif]-->\n" +
                "<link type=\"text/css\" href=\"http://b.rupeetigerloan.com:8080/statics/css/jquery-ui-1.10.0.custom.css\" rel=\"stylesheet\" />\n" +
                "<link rel=\"stylesheet\" href=\"/statics/css/member/style.css\">\n" +
                "<script src=\"http://b.rupeetigerloan.com:8080/statics/scripts/lib/jquery.js\" ></script>\n" +
                "<script src=\"http://b.rupeetigerloan.com:8080/statics/scripts/lib/jquery-ui-1.10.0.custom.min.js\"></script>\n" +
                "<script src=\"http://b.rupeetigerloan.com:8080/statics/scripts/lib/jquery.datetimepicker.js\"></script>\n" +
                "<script src=\"http://b.rupeetigerloan.com:8080/statics/scripts/lib/jquery.validationEngine-zh_CN.js\" ></script>\n" +
                "<script src=\"http://b.rupeetigerloan.com:8080/statics/scripts/lib/jquery.validationEngine.js\" ></script>\n" +
                "<script src=\"http://b.rupeetigerloan.com:8080/statics/scripts/lib/global.js\"></script>\n" +
                " <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->\n" +
                "    <!--[if lt IE 9]><script src=\"http://v3.bootcss.com/assets/js/ie8-responsive-file-warning.js\"></script><![endif]-->\n" +
                "    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->\n" +
                "    <!--[if lt IE 9]>\n" +
                "      <script src=\"http://cdn.bootcss.com/html5shiv/3.7.0/html5shiv.js\"></script>\n" +
                "      <script src=\"http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js\"></script>\n" +
                "    <![endif]-->\n" +
                "</head>\n" +
                "<body >\n" +
                "<div class=\"dialog\">\n" +
                "        <div class='panel panel-default'>\n" +
                "            <div class='panel-body'>\n" +
                "                <table class=\"table report_table\">\n" +
                "                    <tr>\n" +
                "                        <td>客户</td>\n" +
                "                        <td>联系人电话</td>\n" +
                "                        <td>总金额</td>\n" +
                "                    </tr>\n" +
                "                                        <tr>\n" +
                "                        <td>Partha Mandal</td>\n" +
                "                        <td>7001089889</td>\n" +
                "                        <td>2600.00</td>\n" +
                "                    </tr>\n" +
                "                                        <tr>\n" +
                "                        <td>Khambha Mahendrakumar Chamanla</td>\n" +
                "                        <td>8140455096</td>\n" +
                "                        <td>4000.00</td>\n" +
                "                    </tr>\n" +
                "                                    </table>\n" +
                "            </div>\n" +
                "        </div>\n" +
                "</div></body>\n" +
                "</html>\n";
        LOGGER.info("== RupeeTiger还款详情 ==,result:{}", extResult);
        Document extDocument = Jsoup.parse(extResult);
        Elements extTtrs = extDocument.select("table").select("tr");
        if (extTtrs.size() <= 0) {
            return;
        }
        JSONArray repayList = new JSONArray();

        for (int i = 1; i < extTtrs.size(); i++) {
            Elements tds = extTtrs.get(i).select("td");
            JSONObject detail = new JSONObject();
            for (int j = 0; j < tds.size(); j++) {
                if (tds.get(j).childNodes().size() <= 0) {
                    continue;
                }
                String value = tds.get(j).childNodes().get(0).toString();
                if (j == 0) {
                    detail.put("name", value);
                } else if (j == 1) {
                    detail.put("phone", value);
                } else if (j == 2) {
                    detail.put("amount", value);
                }
            }
            repayList.add(detail);
        }
        LOGGER.info("====", repayList.toString());
    }

    private static String getBirthDayByAge(Integer age) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        c.setTime(new Date());
        c.add(Calendar.YEAR, -age);
        Date y = c.getTime();
        return format.format(y);
    }
}
